package com.kwlt.smc.util;

import java.io.IOException;

import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class ModelConvJson<T>{
	
	private ObjectMapper objectMapper = null;
	
	public T getModelObject(Map<String,String> map,Class<T> cl){
		objectMapper = new ObjectMapper();
		T t = null;
		try {
			Writer strWriter = new StringWriter(); 
			objectMapper.writeValue(strWriter, map);
			t = objectMapper.readValue(strWriter.toString(),cl);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return t;
	}
	
	
	public T getModelObject(String json,Class<T> c){
		objectMapper = new ObjectMapper();
		T t = null;
		try {
			t = objectMapper.readValue(json,c);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return t;
	}
	
	public Map<String,Object> getModelMap(Object obj){
		objectMapper = new ObjectMapper();
		Writer strWriter = new StringWriter(); 
		Map<String,Object> map = null;
		try {
			objectMapper.writeValue(strWriter, obj);
			map = objectMapper.readValue(strWriter.toString(), Map.class);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}
	
	public String getJson(Object obj){
		objectMapper = new ObjectMapper();
		Writer strWriter = new StringWriter(); 
		try {
			objectMapper.writeValue(strWriter, obj);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return strWriter.toString();
	}

}
